/**
 * post 请求 获取post data
 */

// 引入 http 模块
const http = require('http')
const querystring = require('querystring')

// 创建服务
const server = http.createServer((req, res) => {
  const { method = '', url = '' } = req
  const path = url.split('?')[0]
  const query = querystring.parse(url.split('?')[1])

  // 设置返回格式为 json
  res.setHeader('Content-type', 'application/json')
  
  // 返回的数据
  let resData = {
    method,
    url,
    path,
    query
  }

  // 返回
  if (method === 'GET') {
    res.end(JSON.stringify(resData))
  }

  if (method === 'POST') {
    let postData = ''
    
    req.on('data', chunk => {
      postData += chunk.toString()
    })

    req.on('end', () => {
      resData.postData = JSON.parse(postData)
      console.log('resData --- ', resData)
      res.end(JSON.stringify(resData))
    })
  }
})

// 监听端口
server.listen(8000)
console.log('监听了端口8000: http://192.168.10.51:8000')